package edu.whu.powersoap;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.mapapi.cloud.CloudListener;
import com.baidu.mapapi.cloud.CloudManager;
import com.baidu.mapapi.cloud.CloudPoiInfo;
import com.baidu.mapapi.cloud.CloudSearchResult;
import com.baidu.mapapi.cloud.DetailSearchResult;
import com.baidu.mapapi.cloud.LocalSearchInfo;

import edu.whu.powersoap.UserProvider;
import edu.whu.powersoap.R;

public class MenuActivity extends Activity implements CloudListener {

	private static final String TAG = "MenuActivity";

	private LayoutInflater mLayoutInflater;
	private UserInfo mCurrentUser;
	int count = 0; 
	ProgressDialog progressDialog = null;
	String del_name;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_menu);

		CloudManager.getInstance().init(MenuActivity.this);

		mLayoutInflater = LayoutInflater.from(this);
		mCurrentUser = ((GlobalApplication) getApplication()).getLoginUser();

		Button btn;
		btn = (Button) findViewById(R.id.base_map_demo);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(MenuActivity.this,
						PoiListActivity.class));

			}

		});

		btn = (Button) findViewById(R.id.user_change_password);
		if (btn != null) {
			btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					final View userChangePasswordView = mLayoutInflater
							.inflate(R.layout.user_change_password, null);

					Dialog dialog = new AlertDialog.Builder(MenuActivity.this)
							.setTitle("修改密码")
							.setView(userChangePasswordView)
							.setPositiveButton("确认",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {

											EditText input;
											input = (EditText) userChangePasswordView
													.findViewById(R.id.password_edit);
											String password = input.getText()
													.toString();
											input = (EditText) userChangePasswordView
													.findViewById(R.id.password_confirm_edit);
											String password_confirm = input
													.getText().toString();
											CheckBox isAdmin = (CheckBox) userChangePasswordView
													.findViewById(R.id.is_admin);
											long flag = 0;
											if (isAdmin.isChecked()){
												flag |= UserInfo.FLAG_ADMIN;
												
											}
											if ((password == null)
													|| !password
															.equals(password_confirm)) {
												showHintDialog("提示",
														"修改密码失败, 密码不一致!");
												return;
											}
											
											UserProvider.changeFlag(MenuActivity.this, mCurrentUser.getName(), flag);
											UserProvider.changePassword(
													MenuActivity.this,
													mCurrentUser.getName(),
													password);
											showHintDialog("提示", "修改密码成功");
										}
									})
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											dialog.dismiss();
										}
									}).create();

					dialog.show();

				}

			});
		}

		//用户删除待完善
		String username = MainActivity.user;
		Cursor cur = MenuActivity.this.getContentResolver().query(UserProvider.CONTENT_URI, new String[]
				{
					UserProvider.VOL_ID + " as _id",
					UserProvider.VOL_NAME,
					UserProvider.VOL_FLAG
				}, "name =?", new String[]{username}, null);
		cur.moveToFirst();
		int id = cur.getColumnIndex(UserProvider.VOL_FLAG);
		final String flag = cur.getString(id);
		cur.close();
		btn = (Button) findViewById(R.id.user_del);
		
		if(btn != null){
			btn.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0){
					Cursor cursor = MenuActivity.this.getContentResolver().query(UserProvider.CONTENT_URI, new String[]
							{
								UserProvider.VOL_ID + " as _id",
								UserProvider.VOL_NAME,
								UserProvider.VOL_PASSWORD,
								UserProvider.VOL_FLAG
							}, null, null, null);
					int j = 0;
					for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
						j++;
					}
					int i = 0;
					final boolean check[] = new boolean[j];
					final String[] name = new String[j];
					final ArrayList<String> del = new ArrayList<String>();
					final HashMap<Boolean , String> hashmap = new HashMap<Boolean , String>();
					
					for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
						int id = cursor.getColumnIndex(UserProvider.VOL_NAME);
						String name0 = cursor.getString(id);
						name[i] = name0;
						check[i] = false;
						hashmap.put(check[i], name[i]);
						i++;
					}
					
					if(Integer.valueOf(flag) == 1){
						Dialog dialog = new AlertDialog.Builder(MenuActivity.this)
						.setTitle("删除用户")
						.setIcon(R.drawable.alert_dialog_icon)
						.setMultiChoiceItems(
								name, 
								check,
								new DialogInterface.OnMultiChoiceClickListener() 
								{
									public void onClick(DialogInterface dialog,
											int whichButton,
											boolean isChecked)
									{
										if(isChecked){
											check[whichButton] = true;
											hashmap.put(check[whichButton], name[whichButton]);
											del_name = hashmap.get(true);
											del.add(del_name);
										}else{
											check[whichButton] = false;
										}
										
										
									}
								})
					.setPositiveButton("delete", new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int whichButton){
//							String del_name = hashmap.get(true);
							for(int m = 0; m < del.size(); m++){
								UserProvider.deleteUser(MenuActivity.this, del.get(m));
							}
													
						}
					})
					.setNegativeButton("cancel", new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int whichButton){
							dialog.dismiss();
						}
					}).create();
					
					dialog.show();
				}else{
					final Dialog dialog1 = new AlertDialog.Builder(MenuActivity.this)
					.setMessage("你没有足够权限")
					.setTitle("提示")
					.setPositiveButton("确认",
					new DialogInterface.OnClickListener() {		
					@Override
					public void onClick(DialogInterface dialog1, int which) 
					{
						dialog1.dismiss();
					}
					}).create();
						
					dialog1.show();
				}
				
				}
				});
			
			}
		
		btn = (Button) findViewById(R.id.job_create);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(Integer.valueOf(flag) == 1){				
					startActivity(new Intent(MenuActivity.this,
						JobCreateActivity.class));}else{
							final Dialog dialog1 = new AlertDialog.Builder(MenuActivity.this)
							.setMessage("你没有足够权限")
							.setTitle("提示")
							.setPositiveButton("确认",
							new DialogInterface.OnClickListener() {		
							@Override
							public void onClick(DialogInterface dialog1, int which) 
							{
								dialog1.dismiss();
							}
							}).create();
							
							dialog1.show();					
						}
			}

		});

		btn = (Button) findViewById(R.id.job_list_not_finish);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {				
					startActivity(new Intent(MenuActivity.this,
							JobListActivity.class));
				
			}

		});

		btn = (Button) findViewById(R.id.job_list_finished);
		btn.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				startActivity(new Intent(MenuActivity.this,
						JobFinishedListActivity.class));

			}

		});
		
		btn = (Button) findViewById(R.id.delete_map_data);
		btn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Context mContext = MenuActivity.this;
				ContentResolver cr = mContext.getContentResolver();
				int count = cr.delete(PoiProvider.CONTENT_URI, null, null);
				showHintDialog("提示", "您清空了"+ count +"条数据");
			}

		});
		
		
		btn = (Button) findViewById(R.id.import_map_data);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				File file = new File(Environment.getExternalStorageDirectory()
						.getPath() + "/1.xls");
				File file_2 = new File(Environment.getExternalStorageDirectory()
						.getPath() + "/2.xls");
				if (!file.exists()) {
					showHintDialog("提示", "未找到数据文件！");
					return;
				}
				try {
					
		            Workbook wb = Workbook.getWorkbook(file);
		            WritableWorkbook wrb = Workbook.createWorkbook(file_2);
		            final WritableSheet wrs  = wrb.createSheet("first",0);
					Sheet[] sheets = wb.getSheets();
					int totalRows = 0;
					
					//sheets预处理
					int m = 0;
					for(Sheet sheet : sheets){
						int[] rows = new int[500];
						int rows_m = wrs.getRows();;
						rows[m] = sheets[m].getRows();
						if(m != 0){
							rows[m] = rows[m] - 1;
						}
						
						for(int line = 0 ; line < rows[m] ; line++){
							if(m == 0){
								Label label_0 = new Label(0,rows_m,sheets[m].getCell(0, line).getContents());  
								wrs.addCell(label_0);
								Label label_1 = new Label(1,rows_m,sheets[m].getCell(1, line).getContents());  
								wrs.addCell(label_1);
								Label label_2 = new Label(2,rows_m,sheets[m].getCell(2, line).getContents());  
								wrs.addCell(label_2);
								Label label_3 = new Label(3,rows_m,sheets[m].getCell(3, line).getContents());  
								wrs.addCell(label_3);
								Label label_4 = new Label(4,rows_m,sheets[m].getCell(4, line).getContents());  
								wrs.addCell(label_4);
								Label label_5 = new Label(5,rows_m,sheets[m].getCell(5, line).getContents());  
								wrs.addCell(label_5);
								Label label_6 = new Label(0,rows_m,sheets[m].getCell(6, line).getContents());  
								wrs.addCell(label_6);
								Label label_7 = new Label(7,rows_m,sheets[m].getCell(7, line).getContents());  
								wrs.addCell(label_7);
								Label label_8 = new Label(8,rows_m,sheets[m].getCell(8, line).getContents());  
								wrs.addCell(label_8);
								Label label_9 = new Label(9,rows_m,sheets[m].getCell(9, line).getContents());  
								wrs.addCell(label_9);
								Label label_10 = new Label(10,rows_m,sheets[m].getCell(10, line).getContents());  
								wrs.addCell(label_10);
								Label label_11 = new Label(11,rows_m,sheets[m].getCell(11, line).getContents());  
								wrs.addCell(label_11);
								Label label_12 = new Label(12,rows_m,sheets[m].getCell(12, line).getContents());  
								wrs.addCell(label_12);
								Label label_13 = new Label(13,rows_m,sheets[m].getCell(13, line).getContents());  
								wrs.addCell(label_13);
								Label label_14 = new Label(14,rows_m,sheets[m].getCell(14, line).getContents());  
								wrs.addCell(label_14);
								Label label_15 = new Label(15,rows_m,sheets[m].getCell(15, line).getContents());  
								wrs.addCell(label_15);
								Label label_16 = new Label(16,rows_m,sheets[m].getCell(16, line).getContents());  
								wrs.addCell(label_16);
								Label label_17 = new Label(17,rows_m,sheets[m].getCell(17, line).getContents());  
								wrs.addCell(label_17);
								Label label_18 = new Label(18,rows_m,sheets[m].getCell(18, line).getContents());  
								wrs.addCell(label_18);
							
							    rows_m++;
							}else{
								Label label_0 = new Label(0,rows_m,sheets[m].getCell(0, line+1).getContents());  
								wrs.addCell(label_0);
								Label label_1 = new Label(1,rows_m,sheets[m].getCell(1, line+1).getContents());  
								wrs.addCell(label_1);
								Label label_2 = new Label(2,rows_m,sheets[m].getCell(2, line+1).getContents());  
								wrs.addCell(label_2);
								Label label_3 = new Label(3,rows_m,sheets[m].getCell(3, line+1).getContents());  
								wrs.addCell(label_3);
								Label label_4 = new Label(4,rows_m,sheets[m].getCell(4, line+1).getContents());  
								wrs.addCell(label_4);
								Label label_5 = new Label(5,rows_m,sheets[m].getCell(5, line+1).getContents());  
								wrs.addCell(label_5);
								Label label_6 = new Label(0,rows_m,sheets[m].getCell(6, line+1).getContents());  
								wrs.addCell(label_6);
								Label label_7 = new Label(7,rows_m,sheets[m].getCell(7, line+1).getContents());  
								wrs.addCell(label_7);
								Label label_8 = new Label(8,rows_m,sheets[m].getCell(8, line+1).getContents());  
								wrs.addCell(label_8);
								Label label_9 = new Label(9,rows_m,sheets[m].getCell(9, line+1).getContents());  
								wrs.addCell(label_9);
								Label label_10 = new Label(10,rows_m,sheets[m].getCell(10, line+1).getContents());  
								wrs.addCell(label_10);
								Label label_11 = new Label(11,rows_m,sheets[m].getCell(11, line+1).getContents());  
								wrs.addCell(label_11);
								Label label_12 = new Label(12,rows_m,sheets[m].getCell(12, line+1).getContents());  
								wrs.addCell(label_12);
								Label label_13 = new Label(13,rows_m,sheets[m].getCell(13, line+1).getContents());  
								wrs.addCell(label_13);
								Label label_14 = new Label(14,rows_m,sheets[m].getCell(14, line+1).getContents());  
								wrs.addCell(label_14);
								Label label_15 = new Label(15,rows_m,sheets[m].getCell(15, line+1).getContents());  
								wrs.addCell(label_15);
								Label label_16 = new Label(16,rows_m,sheets[m].getCell(16, line+1).getContents());  
								wrs.addCell(label_16);
								Label label_17 = new Label(17,rows_m,sheets[m].getCell(17, line+1).getContents());  
								wrs.addCell(label_17);
								Label label_18 = new Label(18,rows_m,sheets[m].getCell(18, line+1).getContents());  
								wrs.addCell(label_18);
								
								rows_m++;
							}
						}		
						m++;
					}
					wrb.write();
					wrb.close();
					
					if(wrs != null) {
						Log.v(TAG,
								"name=" + wrs.getName() + ", Columns="
										+ wrs.getColumns() + ", Rows="
										+ wrs.getRows() + ", cell(1,0)="
										+ wrs.getCell(1, 0).getContents());
						if ((wrs.getColumns() != 19)) {
							showHintDialog("提示", "数据文件格式错误！");
							return;
						}

						final int rows = wrs.getRows();
						totalRows += rows - 1;
					     
			            // 创建ProgressDialog对象  
			            progressDialog = new ProgressDialog(MenuActivity.this);                 
			            // 设置进度条风格，风格为长形  
			            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);                 
			            progressDialog.setTitle("ProgressDialog");                
			            progressDialog.setMessage("Data Loading ...");                
			            progressDialog.setIcon(R.drawable.tubiao);  
			            progressDialog.setMax(totalRows);               
			            progressDialog.setIndeterminate(false);               
			            progressDialog.setCancelable(true);              
			            progressDialog.show();                
						
			            new Thread()   
			            {  
			                public void run()  
			                {  
			                    try  
			                    {  
			                    	for (int line = 1; line < rows; line++) {
			                    		
			                    		progressDialog.setProgress(line); 
			                    		
										PoiBean poi = new PoiBean();
										poi.sheet = wrs.getName();
										poi.geo_id = wrs.getCell(1, line).getContents();
										poi.dev_id = wrs.getCell(2, line).getContents();
										poi.system_id = wrs.getCell(3, line)
												.getContents();
										poi.name = wrs.getCell(4, line).getContents();
										poi.feeder_line = wrs.getCell(5, line)
												.getContents();
										poi.tower_material = wrs.getCell(6, line)
												.getContents();
										poi.tower_type = wrs.getCell(7, line)
												.getContents();
										poi.high_low_voltage = wrs.getCell(8, line)
												.getContents();
										poi.circuit_count = wrs.getCell(9, line)
												.getContents();
										poi.operating_company = wrs.getCell(10, line)
												.getContents();
										poi.maintain_group = wrs.getCell(11, line)
												.getContents();
										poi.operating_status = wrs.getCell(12, line)
												.getContents();
										poi.asset_company = wrs.getCell(13, line)
												.getContents();
										poi.asset_property = wrs.getCell(14, line)
												.getContents();
										poi.urban_rural = wrs.getCell(15, line)
												.getContents();
										poi.geooid = wrs.getCell(16, line).getContents();
										
										poi.x = Double.valueOf(wrs.getCell(17, line).getContents());
										poi.y = Double.valueOf(wrs.getCell(18, line).getContents());

										PoiProvider.addPoi(MenuActivity.this, poi);
									}
			                    }finally{
			                    	progressDialog.cancel();
			                    }
			                }
			            }.start();  
					}
				} catch (BiffException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (RowsExceededException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (WriteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});

		super.onCreate(savedInstanceState);
	}

	@Override
	public void onGetDetailSearchResult(DetailSearchResult result, int error) {
		Log.i(TAG, "onGetDetailSearchResult, result=" + result + ", error="
				+ error);
		if (result != null) {
			if (result.poiInfo != null) {
				Toast.makeText(MenuActivity.this, result.poiInfo.title,
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(MenuActivity.this, "status:" + result.status,
						Toast.LENGTH_SHORT).show();
			}
		}

	}

	@Override
	public void onGetSearchResult(CloudSearchResult result, int error) {
		if (result != null && result.poiList != null
				&& result.poiList.size() > 0) {
			Log.i(TAG,
					"onGetSearchResult, result length: "
							+ result.poiList.size());

			for (CloudPoiInfo info : result.poiList) {
				Log.d(TAG, "info=" + info);
			}

		}

	}

	private void showHintDialog(String title, String msg) {
		new AlertDialog.Builder(MenuActivity.this).setTitle(title)
				.setMessage(msg)
				.setPositiveButton("确认", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).show();
	}

}
